const { Service } = require('egg')
// const { tableToList } = require('../utils/tools')
const cheerio = require('cheerio')

module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @param sid
   * @return {Array} *
   */
  async table(sid) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl1 = `${this.ctx.state.baseUrl}/jwglxt/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default`
    const apiUrl2 = `${this.ctx.state.baseUrl}/jwglxt/xtgl/comm_cxZydmList.html`
    const apiUrl3 = `${this.ctx.state.baseUrl}/jwglxt/xjyj/xjyj_cxXjyjjdlb.html?gnmkdm=N105505`
    const header = ['名称', '学分', '类别']
    const nj = `20${sid.substring(0, 2)}`
    let zy = 0
    let jgId = 0
    let zyhId = 0

    // 第一次请求，请求学籍信息，获得专业
    const res1 = await this.ctx.curl(apiUrl1, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 5000,
    })
    if (res1.status === 200) {
      try {
        const pageXml1 = res1.data.toString()
        const $ = cheerio.load(pageXml1)
        zy = $('#col_zyh_id').text().replace(/\s/g, '')
      } catch (err) {
        return err
      }
    }

    // 第二次请求，请求培养计划之前，获得jg_id，zyh_id
    const res2 = await this.ctx.curl(apiUrl2, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 5000,
    })
    if (res2.status === 200) {
      try {
        const pageXml2 = res2.data.toString()
        const data2 = JSON.parse(pageXml2)
        const foundItem = data2.find((item) => item.zymc === zy)

        if (foundItem) {
          jgId = foundItem.jg_id
          zyhId = foundItem.zyh_id
        } else {
          jgId = ''
          zyhId = ''
        }
      } catch (err) {
        console.log('err', err)
        return err
      }
    }

    // 第三次请求，请求培养计划
    const res = await this.ctx.curl(apiUrl3, {
      method: 'POST',
      data: {
        jg_id: jgId,
        njdm_id: nj,
        zyh_id: zyhId,
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      timeout: 5000,
    })

    if (res.status === 200) {
      try {
        const data = JSON.parse(res.data.toString())
        if (data === undefined || data.length === 0) {
          return { table: {}, time: [] }
        }
        // 开始处理
        const detail = []// 存放各个学期具体的修读信息
        const uniqueSemesters = new Set()// 创建一个 Set 来存储唯一的学期
        let temp = []
        let xq = []
        const dataJson = {}// 存放json对象
        for (const i of data) {
          for (const key in i) {
            if (key !== 'kcList' && key !== 'xfyqjdmc') { // 删除无关信息
              delete i[key]
            }
          }
        }
        for (const i of data) {
          if (Array.isArray(i.kcList)) {
            for (const j of i.kcList) {
              for (const key in j) {
                if (key === 'kcmc' || key === 'jyxdxnmc' || key === 'jyxdxqmc' || key === 'xf') { // 将每门课的修读情况的值存入一个数组
                  temp.push(j[key])
                }
              }
              temp.push(i.xfyqjdmc)
              detail.push(temp)
              temp = []
            }
          } else {
            temp.push([])
            temp.push(i.xfyqjdmc)
            detail.push(temp)
            temp = []
          }
        }
        for (const i of detail) { // 构造学期，将学年和学期拼接
          const v = `${i[0]}-${i[1]}`
          i.splice(0, 2)
          i.push(v)
        }

        detail.forEach((item) => { // 遍历数组，提取并添加学期到 Set 中
          const semester = item[item.length - 1]
          if (semester !== undefined) {
            uniqueSemesters.add(semester)
          }
        })
        xq = Array.from(uniqueSemesters)// 将 Set 转换为数组
        const xqUp = xq.filter((item) => /^2/.test(item))// 过滤掉开头不是 2 的字符串
        const dataArr = Array.from({ length: xqUp.length }, () => [])

        for (const item of detail) {
          const index = xqUp.indexOf(item[item.length - 1])// 根据学期大小，创建各个学期的数组，用于存放各个学期的数据
          if (index !== -1) { // 将对应学期数据存入对应数组
            dataArr[index].push(item)
          }
          item.splice(item.length - 1, 1)// 删除学期信息
        }

        for (let i = 0; i < xq.length; i++) {
          dataJson[xqUp[i]] = dataArr[i]// 构建json对象
        }

        return { table: dataJson, header }
      } catch (err) {
        console.log('err', err)
        return err
      }
    }
    return { table: {}, header }
  }

  // /**
  //  * * 培养计划存储
  //  * @param data
  //  */
  // async tableSave(data) {
  //   const collection = uniCloud.database().collection('E-student-plan')
  //   const res = await collection.where({
  //     student_id: this.ctx.data.sid, campus_id: this.ctx.state.campusId,
  //   }).count()
  //   if (res.total === 0) {
  //     await collection.add({
  //       campus_id: this.ctx.state.campusId,
  //       student_id: this.ctx.data.sid,
  //       data,
  //     })
  //   } else {
  //     await collection.where({
  //       student_id: this.ctx.data.sid, campus_id: this.ctx.state.campusId,
  //     }).update({
  //       data,
  //     })
  //   }
  //   return res
  // }
}
